package com.xdxc.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Configuration
public class CorsConfiguration {

    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange exchange, WebFilterChain chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            // 如果是预检请求（OPTIONS），直接返回成功响应
            if (CorsUtils.isPreFlightRequest(request)) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }

            // 设置跨域响应头
            HttpHeaders headers = response.getHeaders();
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // 允许所有域名访问
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS"); // 允许的 HTTP 方法
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*"); // 允许的请求头
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); // 是否允许携带 Cookie
            headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"); // 预检请求缓存时间

            // 继续处理请求
            return chain.filter(exchange);
        };
    }
}